package com.ray.export.runner.confirm;

import com.ray.export.empty.Empty;
import com.ray.export.exception.RunnerException;
import com.ray.export.runner.Hander;
import com.ray.export.runner.Runner;
import com.ray.export.runner.RunnerResult;
import com.ray.export.spring.ApplicationContextUtil;
import com.ray.export.strategy.data.DataModel;
import com.ray.export.strategy.file.*;
import com.ray.export.template.ConfirmImportTemplate;
import com.ray.export.template.SyncImportTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.lang.annotation.Annotation;

/**
 * @author bo shen
 * @Description: 文件读取执行者
 * @Class: FileLoadRunner
 * @Package com.ray.runner.confirm
 * @date 2019/11/22 13:32
 * @company <p>杭州传化陆鲸科技有限公司</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
public class FileTemplateRunner implements Runner<Annotation>, Hander {


    @Override
    public RunnerResult doRunner(Annotation annotation, DataModel dataModel, RunnerResult perResult) {
        try {
            if (annotation instanceof SyncImportTemplate) {
                return this.hander(((SyncImportTemplate) annotation).fileTemplate(), dataModel, perResult);
            } else if (annotation instanceof ConfirmImportTemplate) {
                return this.hander(((ConfirmImportTemplate) annotation).fileTemplate(), dataModel, perResult);
            }
            return this.hander(null, dataModel, perResult);
        } catch (Exception e) {
            //异常转换
            throw new RunnerException(e.getMessage(), FileTemplate.class);
        }
    }

    @Override
    public RunnerResult hander(Class<?> fileTemplateClass, DataModel dataModel, RunnerResult perResult) {
        log.info("执行文件模板读取操作");
        if (fileTemplateClass == Empty.class) {
            return new RunnerResult(Empty.class, dataModel,dataModel.getBeforeResult());
        }
        //判读配置是否符合规则
        if (!FileTemplate.class.isAssignableFrom(fileTemplateClass)) {
            log.error("文件模板读取配置错误");
            throw new RuntimeException("文件模板读取调配置错误");
        }
        //获取执行对象
        FileTemplate fileTemplate = (FileTemplate) ApplicationContextUtil.getApplicationContext().getBean(fileTemplateClass);
        if (ObjectUtils.isEmpty(fileTemplate)) {
            log.error("获取执行对象异常[{}]", fileTemplateClass.getName());
            throw new RuntimeException("获取执行对象异常");
        }
        FileTemplateResult successResult = fileTemplate.readTemplate(dataModel);
        if (ObjectUtils.isEmpty(successResult)) {
            log.error("文件模板操作失败");
            throw new RuntimeException("文件模板操作失败");
        }
        dataModel.getImportConfirm().setPages(successResult.getPages());
        return new RunnerResult(FileTemplate.class, dataModel, successResult);
    }
}
